package com.longjianghuasheng.logistics.business.release_record

import android.os.Bundle
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.lifecycle.viewModelScope
import com.blankj.utilcode.util.TimeUtils
import com.longjianghuasheng.logistics.R
import com.longjianghuasheng.logistics.base.BaseTitleFragment
import com.longjianghuasheng.logistics.business.detail.WarehousingAdapter
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.IN_FORM
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.OUT_FORM
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.PASS_FORM
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.SELF_FORM
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.STORAGE_FORM1
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.STORAGE_FORM2
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.STORAGE_FORM3
import com.longjianghuasheng.logistics.business.order.fragment.OrderDetailFragment.Companion.STORAGE_FORM4
import com.longjianghuasheng.logistics.databinding.FragmentRecordDetailBinding
import com.longjianghuasheng.logistics.entity.RecordDetailResponse
import com.longjianghuasheng.logistics.eventViewModel
import com.longjianghuasheng.logistics.ext.deleteDialog
import com.longjianghuasheng.logistics.ext.hintDialog
import com.longjianghuasheng.logistics.ext.initGridDecoration
import com.longjianghuasheng.logistics.ext.observer
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import me.hgj.jetpackmvvm.ext.view.gone
import me.hgj.jetpackmvvm.ext.view.visible

class RecordDetailFragment :
    BaseTitleFragment<RecordDetailViewModel, FragmentRecordDetailBinding>() {
    private val warehousingAdapter by lazy {
        WarehousingAdapter()
    }

    private val locationAdapter by lazy {
        WarehousingAdapter()
    }


    override fun layoutId(): Int = R.layout.fragment_record_detail

    override fun initView(savedInstanceState: Bundle?) {
        super.initView(savedInstanceState)
        initTitleBar("记录详情")

        mDatabind.run {

            rvWarehousing.initGridDecoration(
                spanCount = 5,
                space = 8f,
                adapter = warehousingAdapter,
                headFootSpace = 15F

            )
            rvLocation.initGridDecoration(
                spanCount = 5, space = 8f, adapter = locationAdapter, headFootSpace = 15F
            )


            btAgree.setOnClickListener {

                if (mViewModel.isAgree) return@setOnClickListener

                hintDialog("确定同意吗？", {

                    mViewModel.agree()
                })
            }
            btDelete.setOnClickListener {
                deleteDialog {
                    mViewModel.pre_del()
                }
            }
        }

    }

    override fun createObserver() {
        super.createObserver()
        mViewModel.result.observer(this) {

            mDatabind.setData(it)
        }
        mViewModel.notify.observer(this) {

            mViewModel.viewModelScope.launch {

                eventViewModel.onReleaseUpdateEvent.value = 0

                delay(300L)

                navigateUp()

            }
        }
    }

    private fun FragmentRecordDetailBinding.setData(it: RecordDetailResponse) {

        it.run {

            form?.run {

                stvStart.setCenterString(start_address)
                stvEnd.setCenterString(end_address)
                stvName.setCenterString(names)
                stvType.setCenterString(types)
                stvWeight.setCenterString(weights)
                stvVolume.setCenterString(volume)

                stvContainerQuantity.setCenterString(nums2?.ifBlank { nums })
                stvTypeOfContainer.setCenterString(rules2?.ifBlank { rules })
                stvSpecification.setCenterString(rules)


                stvCreateTime.setCenterString(
                    sent_date?.let {
                        if (it.contains("-") || it.contains(".")) {
                            it
                        } else {
                            TimeUtils.millis2String(
                                it.ifBlank { "0" }.toLong() * 1000,
                                "yyyy-MM-dd"
                            )
                        }
                    }


                )

                stvNum.setCenterString(nums)
                stvPackaging.setCenterString(packets)

                stvBonded.setCenterString(add_service1)
                stvAddition.setCenterString(add_service2)

                rgPickupWay.check(if (get_type == 1) R.id.rb_pick_up_from_patron else R.id.rb_to_the_park)


                cbLandCarriage.isChecked = sent_type?.contains("1") ?: false
                cbSeaTransportation.isChecked = sent_type?.contains("2") ?: false
                cbRailway.isChecked = sent_type?.contains("3") ?: false
                cbConsultWith.isChecked = sent_type?.contains("4") ?: false

                rgPlaceOfArrival.check(if (place_type == 1) R.id.rb_fixed_point else R.id.rb_deliver_goods)


            }

            storage?.run {

                if (isNotEmpty()) {
                    first { it.id == form?.sid1 }.isSelected = true
                    warehousingAdapter.setNewInstance(this)

                }
            }
            storage_son?.run {
                if (isNotEmpty()) {
                    first { it.id == form?.sid2 }.isSelected = true
                    locationAdapter.setNewInstance(this)
                }
            }

            order?.run {


                stvGoodsName.setCenterString(goods_name)
                stvLeaseTime.setCenterString(times)
                stvRentalArea.setCenterString(mianji)


                stvAdditionalServices.run {

                    isGone = zjfw.isNullOrBlank()
                    setCenterString(zjfw)
                }


                tvAssess.text = check_type
                mViewModel.isAgree = is_agree == 1
                btAgree.text = if (mViewModel.isAgree) "已同意" else "待同意"
                btAgree.isGone = check_type == "等待评估"


                val visible = {
                    stvContainerQuantity.visible()
                    stvTypeOfContainer.visible()
                }

                val gone1 = {
                    llContainer2.gone()
                    llContainer3.gone()
                    llContainer4.gone()
                }
                val gone2 = {
                    stvSpecification.gone()
                    stvType.gone()
                    llContainer4.gone()

                    stvBonded.visible()
                    stvAddition.visible()
                    stvCreateTime.visible()
                }
                val visiblePackage = { visible: Boolean ->
                    stvPackaging.isVisible = visible

                    stvWeight.isGone = visible
                    stvVolume.isGone = visible
                    stvStart.gone()
                    stvEnd.gone()
                    gone1()
                }
                when (form_type) {
                    IN_FORM -> {
                        rgPickupWay.check(if (form?.type == 1) R.id.rb_pick_up_from_patron else R.id.rb_to_the_park)
                        rbPickUpFromPatron.text = "集装箱取货"

                        rbToThePark.text = "平板车取货"
                        gone2()
                    }
                    OUT_FORM -> {
                        stvVolume.visible()
                        llContainer2.gone()
                        gone2()
                    }
                    SELF_FORM -> {
                        stvSpecification.gone()
                        stvNum.gone()
                    }
                    PASS_FORM -> {

                        stvImportAndExport.run {
                            setCenterString(if (form?.imorex == 1) "进口" else "出口")

                            isGone = form?.imorex == null || form?.imorex == 0

                        }
                        stvOriginalPlace.run {
                            setCenterString(form?.start_address)
                            isGone = form?.start_address.isNullOrBlank()
                        }

                        visiblePackage.invoke(true)
                    }
                    STORAGE_FORM1 -> {
                        llContainer1.gone()
                        gone1.invoke()
                        llContainer5.visible()
                    }
                    STORAGE_FORM2 -> {
                        llContainer1.gone()
                        gone1.invoke()
                        visible.invoke()
                    }
                    STORAGE_FORM3 -> {
                        llContainer1.visible()

                        visiblePackage.invoke(true)
                        visible.invoke()
                    }
                    STORAGE_FORM4 -> {
                        visiblePackage.invoke(true)
                        stvStart.visible()
                        stvEnd.visible()
                        stvName.gone()

                    }
                    else -> {}
                }


            }


        }

        clBg.visible()
    }

    override fun initData() {
        super.initData()
        arguments?.run {

            mViewModel.id = getInt("id")
            when (getString(KEY_TYPE)) {
                TYPE_DETAIL -> {


                }
                TYPE_TO_BE_EVALUATED -> {


                    mDatabind.tvAssess.text = "等待评估"
                }
                else -> {}
            }

        }

    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        mViewModel.pre_order_show()
    }

    companion object {
        const val KEY_TYPE = "type"
        const val TYPE_DETAIL = "detail"
        const val TYPE_TO_BE_EVALUATED = "toBeEvaluated"

    }

}